import crypto from 'crypto';
import { Request, Response, NextFunction, RequestHandler } from 'express';

const SECRET_KEY = process.env.SECRET_KEY || 'default-secret-key';

function generateSignature(data: string): string {
  return crypto.createHmac('sha256', SECRET_KEY).update(data).digest('hex');
}

const verifySignature: RequestHandler = (req: Request, res: Response, next: NextFunction): void => {
  const signature = req.headers['x-signature'];
  const timestamp = req.headers['x-timestamp'];

  if (!signature || !timestamp) {
    res.status(400).json({ error: 'Missing signature or timestamp' });
    return;
  }

  const bodyString = JSON.stringify(req.body);
  const dataToSign = `${timestamp}.${bodyString}`;

  const computedSignature = generateSignature(dataToSign);

  if (computedSignature !== signature) {
    res.status(401).json({ error: 'Invalid signature' });
    return;
  }

  next();
};

export default verifySignature;
